"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    Q = require('q');

function ReferenceService() {
    console.log("ReferenceService constructor");
}
ReferenceService.prototype = Object.create(TokenService.prototype);
ReferenceService.prototype.constructor = ReferenceService;

ReferenceService.prototype.search = function (request, response, promise) {
    return promise.then(function (self) {
        
        var skip = parseInt(request.query.skip);
        var limit = parseInt(request.query.limit);
        var query = request.query.login;

        return self.mongoGetStartsWithLogin(query, { skip: skip, limit: limit}).then(function (references) {
            return response.send({ request: request, content: references });
        });
    });
};

//ReferenceService.prototype.getPageByLogin = function (request, response, promise) {
//    return promise.then(function (self) {
//        var login = decodeURIComponent(request.params.login);
//        return self.mongoGetByLogin(login).then(function(reference){
//            if(reference.type == "shop"){
//                return require("./shopservice").mongoGetPageById(reference.referenceId).then(function (shop) {
//                    var content = {
//                        type: "shop",
//                        login: shop.login,
//                        shop: shop
//                    }
//                    return response.send({ request: request, content: content });
//                });
//            }
//            else if(reference.type == "user"){
//                return require("./userservice").mongoGetPageById(reference.referenceId).then(function (user) {
//                    var content = {
//                        type: "user",
//                        login: user.login,
//                        user: user
//                    }
//                    return response.send({ request: request, content: content });
//                });
//            }
//            else throw new Error("Reference type: " + reference.type + " is unknown.");
//        });
//    });
//};

/*-------------------------------------------------------*/
/*mongo daf*/

ReferenceService.prototype.mongoGetStartsWithLogin = function (query, options) {
    if (!query) throw new Error("query is not defined.");

    options = options || {};

    var opts = {};
    options = options || {}
    if (options.limit) opts.limit = options.limit;
    if (options.skip) opts.skip = options.skip;
    opts.sort = {"login": 1};

    opts.limit = opts.limit || 20;

    query = query.replace(' ', '\\s');
    var regex = new RegExp("^" + query, "ig");

    return mongo.find('references', { login: { $regex: regex } }, opts).then(function (cursor) {
        return Q.ninvoke(cursor, 'toArray');
    });
};


ReferenceService.prototype.mongoGetByLogin = function (login) {
    if (!login) throw new Error("login is not defined.");

    return mongo.findOne('references', { login: login });
};

ReferenceService.prototype.mongoRemove = function (referenceId, type) {
    if (!referenceId) throw new Error("referenceId is not defined.");
    if (!type) throw new Error("type is not defined.");
    var self = this;

    referenceId = new ObjectId(referenceId);

    return mongo.remove('references', { referenceId:  referenceId, type: type});
}

ReferenceService.prototype.mongoInsert = function (login, referenceId, type) {
    if (!login) throw new Error("login is not defined.");
    if (!referenceId) throw new Error("referenceId is not defined.");
    if (!type) throw new Error("type is not defined.");
    var self = this;

    var reference = {
        login: login,
        referenceId: referenceId,
        type: type
    };

    return mongo.insert('references', reference).then(function (data) {
        return data[0];
    });
};

ReferenceService.prototype.mongoUnauthorizedLogin = function (login) {
    if (!login) throw new Error("login is not defined.");
    var self = this;

    var reference = {
        login: login
    };

    return mongo.insert('references.unauthorized', reference).then(function (data) {
        return data[0];
    });
};

ReferenceService.prototype.mongoIsLoginAuthorized = function (login) {
    if (!login) throw new Error("login is not defined.");

    return mongo.findOne('references.unauthorized', { login: login }).then(function (res) {
        if (res) throw new Error("Login is not authorized.");
        return mongo.findOne('references', { login: login }).then(function (res) {
            if (res) throw new Error("Login already exists.");
            return true;
        });
    });
};


exports = module.exports = new ReferenceService();